""" 
Lines 11 through 63 is modified code from auto echo. 
Modified by: Karl Zigler
"""
import json
import urllib2
import os
import pickle

from optparse import OptionParser
from twitter.oauth import read_token_file

DEFAULT_USERNAME = 'TWlTTERWHALE'
DEFAULT_AUTH_FILENAME = '.twitter_oauth' 
DEFAULT_LASTID_FILENAME = '.twitter_lastid'
DEFAULT_STATUS_FILENAME = '.statuses.txt'
if __name__ == '__main__':
    thelist = []
    filelist = []
    #JFM: using OptionParser - see http://docs.python.org/release/2.6.6/library/optparse.html
    # allowing user to specify a username and/or oauth file, in addition to lastid
    parser = OptionParser()
    parser.add_option('-s', '--statusfile', dest='statusfile')
    parser.add_option('-u', '--username', dest='username')
    parser.add_option('-o', '--oauthfile', dest='oauthfile')
    parser.add_option('-l', '--lastid', dest='lastid')
    (options, args) = parser.parse_args()
    
    home_dir = os.environ.get('HOME', '')
    
    if options.username:
        username = options.username   
    else:
        username = DEFAULT_USERNAME

    if options.statusfile:
        statusfile = options.statusfile
        username_filename = home_dir + os.sep + statusfile
    else:
        username_filename = home_dir + os.sep + '.statuses.txt'
        try:
            with open(username_filename, 'r') as f:
                filelist = pickle.load(f)
            f.close()
            for i in range(len(filelist)):
                if (filelist[i] not in thelist):
                    thelist.append(filelist[i])
        except IOError:
            thelist = []
            
    if options.oauthfile:
        oauth_filename = options.oauthfile
    else:
        oauth_filename = home_dir + os.sep + DEFAULT_AUTH_FILENAME
    oauth_token, oauth_token_secret = read_token_file(oauth_filename)
        
    if options.lastid:
        lastid = options.lastid
        lastid_filename = home_dir + os.sep + DEFAULT_LASTID_FILENAME + username
    else:
        #JFM: use a file to store / restore the state of lastid between invocations
        lastid_filename = home_dir + os.sep + DEFAULT_LASTID_FILENAME + username
        try:
            with open(lastid_filename, 'r') as f:
                lastid = f.readline()
            f.close()
        except IOError:
            lastid = ''
        #JFM: user may or may not use an '@' prefix for the username, but we'll need it for the search
    if username[0] != '@':
        username = '@' + username
    theid = lastid      
    response = urllib2.urlopen('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' + username)
    friends_str = response.read()
    friends_obj = json.loads(friends_str)
    for i in range(len(friends_obj)):          
        tweet = friends_obj[i]
        tweetstring = {'text': tweet['text']}
        stringer = []
        stringer = list(tweetstring['text'])
        if (tweetstring not in thelist) and ('@' not in stringer) and ('?' in stringer):
            lastid = tweetstring['text'].encode('utf8')
            thelist.append(tweetstring)            
        if (len(thelist) == 20):
            thelist.reverse() 
    with open(username_filename, 'w') as f:
        pickle.dump(thelist, f)
    f.close()  
    with open(lastid_filename, 'w') as f:
        f.write(lastid)
    f.close()      
    for i in thelist:
        print i['text'].encode('utf8')
    print 'current length: ', len(thelist)
    if(theid == lastid):
        print 'No results this time...'        